package org.example

import jetbrains.datalore.plot.PlotSvgExport
import org.jetbrains.letsPlot.export.ggsave
import org.jetbrains.letsPlot.geom.geomDensity
import org.jetbrains.letsPlot.intern.Plot
import org.jetbrains.letsPlot.intern.toSpec
import org.jetbrains.letsPlot.letsPlot
import java.awt.Desktop
import java.io.File

object DemoUtilKt {
    fun createPlot(): Plot {
        val rand = java.util.Random()
        val n = 200
        val data = mapOf<String, Any>(
            "x" to List(n) { rand.nextGaussian() }
        )

        return createPlot(data)
    }

    fun save(plot: Plot) {
        val ggsave = ggsave(plot, "test.png")
        println("path: ${ggsave}")
    }

    fun createPlot(data: Map<String, Any>): Plot {
        val geomDensity = geomDensity(
            color = "dark-green",
            fill = "green",
            alpha = .3,
            size = 2.0
        ) { x = "x" }
        return letsPlot(data).plus(geomDensity)
    }

    fun openInBrowser(content: String) {
        val dir = File(System.getProperty("user.dir"), "lets-plot-images")
        dir.mkdir()
        val file = File(dir.canonicalPath, "my_plot.html")
        file.createNewFile()
        file.writeText(content)

        Desktop.getDesktop().browse(file.toURI())
    }

    fun openInBrowser(plot: Plot) {
        val content = PlotSvgExport.buildSvgImageFromRawSpecs(plot.toSpec())
        openInBrowser(content)
    }

    fun generatSvg() {
        val p = createPlot()

        // Export to SVG.
        // Note: if all you need is to save SVG to a file than you can just use the 'ggsave()' function.
        val content = PlotSvgExport.buildSvgImageFromRawSpecs(p.toSpec())
        openInBrowser(content)
    }
}